//
//  XTXHearViewController.m
//  陪我V聊
//
//  Created by 余清巍 on 2018/7/24.
//  Copyright © 2018年 陪我V聊. All rights reserved.
//

#import "XTXHearViewController.h"
#import "XTXLuzhiyuyinViewController.h"
#import "XTXHearCell.h"
#import "XTXVoiceModel.h"
#import "XTXXQViewController.h"
#import <MJExtension.h>

@interface XTXHearViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,XTXHearCellDelegate>

@property (nonatomic, strong) MBProgressHUD *progreHub;
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) UIButton *zengjiaBtn;
@property (nonatomic,strong) UILabel *weishangchuangimageLabel;//未上传图片
@property (nonatomic, strong) NSMutableArray *cellArr;
@property (nonatomic, assign) NSUInteger pageInteger;
@property (nonatomic, weak) UIImageView *wuneirongImageView;


@end

@implementation XTXHearViewController

-(NSMutableArray *)cellArr{
    if (_cellArr==nil) {
        _cellArr=[NSMutableArray array];
    }
    return _cellArr;
}
-(NSMutableArray *)voiceArr{
    if (_voiceArr==nil) {
        _voiceArr=[NSMutableArray array];
    }
    return _voiceArr;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        UITabBarItem* tabItem = [[UITabBarItem alloc]init];
        tabItem.selectedImage =  [[UIImage imageNamed:@"听见on"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        tabItem.image = [[UIImage imageNamed:@"听见off"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        tabItem.title = @"音遇";
        [tabItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgbYanse1(0x82e0ff)} forState:UIControlStateNormal];
        [tabItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgbYanse1(0x5974ff)} forState:UIControlStateSelected];
        self.tabBarItem = tabItem;
        self.title = tabItem.title;
        [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
        
    }
    return self;
}

- (UIImageView *)tongguoViewdedaoImageView:(UIView *)view
{
    if ([view isKindOfClass:[UIImageView class]] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *smatteringrookie = [self tongguoViewdedaoImageView:subview];
        if (smatteringrookie) {
            return smatteringrookie;
        }
    }
    return [[UIImageView alloc] init];;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBar.translucent = YES;
    if (self.typeInt!=1) {
        self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(goback)];
    }
    
}
-(void)goback{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self jieshubofangyinpingshijian];
}

/// 结束播放音频事件
-(void)jieshubofangyinpingshijian{
    for (XTXHearCell *cell in self.cellArr) {
        [cell playVoiceEndAnimation];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    ///界面初始化
    [self jiemianchushihua];
}
///界面初始化
-(void)jiemianchushihua{
    self.pageInteger=1;
    UIImageView* lineView = [self tongguoViewdedaoImageView:self.navigationController.navigationBar];
    lineView.hidden = YES;
    self.view.backgroundColor = XZColor(240,240,240);
    [self.view addSubview:self.collectionView];
    _collectionView.sd_layout.rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0).topSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0);
    if (self.typeInt == 0) {
        self.zengjiaBtn.hidden = YES;
        [XTXGongView zanshifanhuianniubingqiezhixingfanhuianniudedianjishijianClick:@""];
    }else if (self.typeInt == 3){
        self.zengjiaBtn.hidden = YES;
        [XTXGongView zanshifanhuianniubingqiezhixingfanhuianniudedianjishijianClick:@""];
        self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.pageInteger++;
            [self voicedewangluoqingqiu];
        }];
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.pageInteger=1;
            [self voicedewangluoqingqiu];
        }];
        [self.collectionView.mj_header beginRefreshing];
    }else {
        self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.pageInteger++;
            [self mediodewangluoqingqiu];
        }];
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.pageInteger=1;
            [self mediodewangluoqingqiu];
        }];
        [self.collectionView.mj_header beginRefreshing];
    }
    self.collectionView.mj_footer.hidden=YES;
    
    [self zengjiaBtn];
        
    
    
    
    UIImageView *wuneirongImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"无内容图片"]];
    [self.view addSubview:wuneirongImageView];
    _wuneirongImageView=wuneirongImageView;
    [_wuneirongImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
    }];
    _wuneirongImageView.hidden=YES;
    [self.view addSubview:self.weishangchuangimageLabel];
        _weishangchuangimageLabel.sd_layout.heightIs(13).topSpaceToView(self.wuneirongImageView, 20).rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0);
        _weishangchuangimageLabel.hidden = YES;
}
- (void)voicedewangluoqingqiu {
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%lu",(unsigned long)self.pageInteger];
    canshuMutDict[@"user_id"] = self.useID.length?self.useID:XTXGongTool.share.useMode.id;
    NSLog(@"%@",canshuMutDict);
    WeakSelf
    [XTXNetworking networkinglistUserVoicesEveedewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            NSArray *arr=[XTXVoiceModel mj_objectArrayWithKeyValuesArray:dict[@"info"]];
            if (self.pageInteger==1) {
                self.voiceArr=[NSMutableArray arrayWithArray:arr];
                [weakSelf.collectionView.mj_header endRefreshing];
            }else{
                if (arr.count==0) {
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.voiceArr addObjectsFromArray:arr];
                    [weakSelf.collectionView.mj_footer endRefreshing];
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.progreHub hideAnimated:YES afterDelay:0.5];
            [weakSelf.collectionView reloadData];
            [self collectionViewFooterView];
        });
    }];
}

-(void)zengjiaBtnClick
{
    XTXLuzhiyuyinViewController *AddView = [[XTXLuzhiyuyinViewController alloc]init];
    AddView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:AddView animated:YES];
}


-(void)mediodewangluoqingqiu {
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"pack"] = APPLink;
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%lu",(unsigned long)_pageInteger];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkinglistVoicesEveedewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            NSArray *arr=[XTXVoiceModel mj_objectArrayWithKeyValuesArray:dict[@"info"]];
            if (self.pageInteger==1) {
                self.voiceArr=[[NSMutableArray alloc]initWithArray:arr];
            }else{
                [self.voiceArr addObjectsFromArray:arr];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.progreHub hideAnimated:YES afterDelay:0.5];
            [weakSelf.collectionView reloadData];
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView.mj_footer endRefreshing];
            [self collectionViewFooterView];
        });
    }];
}
///判断是否显示
-(void)collectionViewFooterView{
    if (_collectionView.collectionViewLayout.collectionViewContentSize.height>=pingmuGao) {
        _collectionView.mj_footer.hidden=NO;
    }else{
        _collectionView.mj_footer.hidden=YES;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.voiceArr.count > indexPath.row && [[self.voiceArr[indexPath.row] user_id] length] && self.typeInt == 1) {
        XTXXQViewController *infoView = [[UIStoryboard storyboardWithName:@"Info" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass(XTXXQViewController.class)];
        infoView.hidesBottomBarWhenPushed = YES;
        infoView.userID = [self.voiceArr[indexPath.row] user_id];
        [self.navigationController pushViewController:infoView animated:YES];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.voiceArr.count == 0) {
        _weishangchuangimageLabel.hidden = NO;
        _wuneirongImageView.hidden=NO;
    }
    else {
        _weishangchuangimageLabel.hidden = YES;
        _wuneirongImageView.hidden=YES;
    }
    if (self.typeInt==0) {
        if (self.xquserModel.voice.length>0) {
            _weishangchuangimageLabel.hidden = YES;
            _wuneirongImageView.hidden=YES;
            return 1;
        }
    }
    return self.voiceArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XTXHearCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(XTXHearCell.class) forIndexPath:indexPath];
    cell.delegate=self;
    if (self.typeInt==0) {
        cell.userModel=self.xquserModel;
    }else{
        cell.voiceModel=_voiceArr[indexPath.item];
    }
    
    return cell;
    
}

#pragma mark - XTXHearCellDelegate
-(void)collectionViewCell:(XTXHearCell *)collectionViewCell moreBtnTouchEventWithID:(NSString *)user_id{
    if (self.typeInt==3) {
        [XTXGongView showTipMsg:@"不可拉黑举报自己"];
    }else{
        //举报拉黑
        [XTXGongView.share zhanshijubaohelaheijiemianEventClick:user_id withController:self];
    }
}
/// 播放音频的代理方法
/// @param collectionViewCell collectionViewCell
/// @param btn 播放按钮
-(void)collectionViewCell:(XTXHearCell *)collectionViewCell playVoiceBtnTouchEvent:(UIButton *)btn{
    [self.cellArr addObject:collectionViewCell];
}

/// 音频结束结束的代理
/// @param collectionViewCell collectionViewCell
-(void)playEndVoiceEvent:(XTXHearCell *)collectionViewCell{
    [self.cellArr removeObject:collectionViewCell];
}
/// 音频将要开始播放
/// @param collectionViewCell collectionViewCell
-(void)voiceWillBeginplay:(XTXHearCell *)collectionViewCell{
    [self jieshubofangyinpingshijian];
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        CGFloat height=375 *270/pingmuKuan;
        layout.itemSize=CGSizeMake(pingmuKuan, height);
        layout.minimumLineSpacing=0;
        layout.minimumInteritemSpacing=0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, pingmuKuan , pingmuGao) collectionViewLayout:layout];
        [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass(XTXHearCell.class) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass(XTXHearCell.class)];
        //设置代理
        _collectionView.backgroundColor=UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
    }
    return _collectionView;
}
- (UIButton *)zengjiaBtn
{
    if (!_zengjiaBtn) {
        _zengjiaBtn = [[UIButton alloc] init];
        [self.view addSubview:self.zengjiaBtn];
        _zengjiaBtn.sd_layout
        .widthIs(65.0)
        .heightIs(65.0)
        .centerXEqualToView(self.view)
        .bottomSpaceToView(self.view, 20.0);
        [_zengjiaBtn setBackgroundImage:[UIImage imageNamed:@"添加语音"] forState:UIControlStateNormal];
        [_zengjiaBtn addTarget:self action:@selector(zengjiaBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _zengjiaBtn;
}

-(UILabel *)weishangchuangimageLabel{
    if (!_weishangchuangimageLabel) {
        _weishangchuangimageLabel = [UILabel new];
        _weishangchuangimageLabel.font = [UIFont systemFontOfSize:14];
        _weishangchuangimageLabel.textColor = rgbYanse1(0xc8c8c8);
        _weishangchuangimageLabel.textAlignment = NSTextAlignmentCenter;
        _weishangchuangimageLabel.text = @"还没有上传听见";
    }
    return _weishangchuangimageLabel;
}

@end
